package xhwl.insurance.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.android.common.log.XHLog;
import xhwl.android.common.util.IdcardValidator;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.R;
import xhwl.insurance.customView.ChineseEditText;
import xhwl.insurance.customView.PopSelectPic;
import xhwl.insurance.http.api.SaleInfoApi;
import xhwl.insurance.http.api.SubmitFileApi;
import xhwl.insurance.http.api.UploadPicApi;
import xhwl.insurance.http.bean.ImageEvent;
import xhwl.insurance.http.bean.ImageItem;
import xhwl.insurance.http.bean.ReferralPicBean;
import xhwl.insurance.http.bean.resp.ErrorCode;
import xhwl.insurance.http.bean.resp.SaleInfoResp;
import xhwl.insurance.util.DataCleanManager;
import xhwl.insurance.util.ImageDisplayer;
import xhwl.insurance.util.IntentConstants;
import xhwl.insurance.util.NumberJudgeUtils;
import xhwl.insurance.util.PermisionUtils;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;


public class AddPatientVisitsActivity extends BaseActivity implements OnClickListener, PopSelectPic.PopSelectBtnClickListener {
    private static final String TAG = AddPatientVisitsActivity.class.getSimpleName();
    int Year, Month, Day;
    EditText phone;
    ChineseEditText name;
    EditText number;
    TextView sex, date;
    Button submit;
    LinearLayout addPaitenetLayout;
    String person_sex = "";
    TextView tvDesc;
    EditText card_num;
    private String cardprice;
    private String yw_id;
    private String saletype;
//    private static String[] PERMISSION = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private String path;
    private File file1,file2,file3;
    private ImageView id_front,id_back,hmo_pic;
    private int flag;
    private static final int TAKE_PICTURE = 0x000000;
    private String card_front,card_back,card_number_pic;
    private String sale_userid;
    private String sale_mobile;
    private String sale_date;
    private TextView card_name;
    private String card_names;
    private String c_type;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != getIntent().getStringExtra("cardprice"))
            cardprice = getIntent().getStringExtra("cardprice");//价格id_front
        yw_id = getIntent().getStringExtra("yw_id");
        if (null != getIntent().getStringExtra("saletype"))
            saletype = getIntent().getStringExtra("saletype");
        if (null != getIntent().getStringExtra("card_name"))
            card_names = getIntent().getStringExtra("card_name");
        if (null != getIntent().getStringExtra("c_type"))
            c_type = getIntent().getStringExtra("c_type");
        setContentView(R.layout.activity_add_patient_visits);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initViews() {
        initTitleViews();
        addPaitenetLayout = (LinearLayout) findViewById(R.id.addpaitenetlayout);
        name = (ChineseEditText) findViewById(R.id.add_paitent_name);
        number = (EditText) findViewById(R.id.add_paitent_number);
        phone = (EditText) findViewById(R.id.add_paitent_phone);
        sex = (TextView) findViewById(R.id.add_paitent_sex);
        date = (TextView) findViewById(R.id.add_paitent_date);
        card_name = (TextView) findViewById(R.id.card_name);
        submit = (Button) findViewById(R.id.submit);
        tvDesc = (TextView) findViewById(R.id.tvDesc);
        card_num = (EditText) findViewById(R.id.card_num);
        id_front = (ImageView) findViewById(R.id.id_front);
        id_back = (ImageView) findViewById(R.id.id_back);
        hmo_pic = (ImageView) findViewById(R.id.hmo_pic);
        card_name.setText(card_names);
        tvDesc.setText(R.string.hmocardsalenotice);
    }

    @Override
    public void initListener() {
        // TODO Auto-generated method stub
        submit.setOnClickListener(this);
        id_front.setOnClickListener(this);
        id_back.setOnClickListener(this);
        hmo_pic.setOnClickListener(this);
        number.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                if (s.length() == 18) {
                    String idNumber = s.toString();
                    String returnMsg = IdcardValidator.validate18Idcard(idNumber);
                    if (StringUtil.isEmpty(returnMsg)) {
                        try {
                            String strYear = idNumber.substring(6, 10);// 年份
                            String strMonth = idNumber.substring(10, 12);// 月份
                            String strDay = idNumber.substring(12, 14);// 月份
//                            date.setText(strYear + "-" + strMonth + "-" + strDay);
                            Year = Integer.parseInt(strYear);
                            Month = Integer.parseInt(strMonth);
                            Day = Integer.parseInt(strDay);
                            String sexStr = idNumber.substring(15, 17);
                            int sex = Integer.parseInt(sexStr);
                            if (sex % 2 == 0) {
                                person_sex = "1";
                                AddPatientVisitsActivity.this.sex.setText("女");
                            } else {
                                person_sex = "0";
                                AddPatientVisitsActivity.this.sex.setText("男");
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            ToastUtil.showToast(mContext, e.getMessage());
                        }
                    } else {
                        ToastUtil.showToast(mContext, returnMsg);
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11 && !NumberJudgeUtils.isMobileNO(phone.getText().toString())) {
                    ToastUtil.showToast(mContext, "手机号格式错误，请输入正确的手机号");
                }
            }
        });
    }

    @Override
    protected void setUpTitleView() {
        // TODO Auto-generated method stub
        super.setUpTitleView();
        titleTextView.setText("填写购买信息");
    }

    @Override
    protected void processOper() {
        // TODO Auto-generated method stub
        sale_date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
        getSaleInfo();
    }

    @Override
    public void loadData() {
        // TODO Auto-generated method stub
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.id_front:
                flag = 1;
                PopSelectPic popfront = new PopSelectPic(this, id_front);
                popfront.setCallBack(this);
                break;
            case R.id.id_back:
                flag = 2;
                PopSelectPic popback = new PopSelectPic(this, id_back);
                popback.setCallBack(this);
                break;
            case R.id.hmo_pic:
                flag = 3;
                PopSelectPic pophmo = new PopSelectPic(this, id_back);
                pophmo.setCallBack(this);
                break;
            case R.id.submit://添加被保障人
                if (vilidInput()) {
                    getpicture();
                }
                break;
        }
    }

    private void getpicture() {
        if(file1==null||file2==null||file3==null)
        {
            return;
        }
        final List<File> fileList=new ArrayList<>();

        fileList.add(file1);
        fileList.add(file2);
        fileList.add(file3);

        final UploadPicApi api = new UploadPicApi(mContext, fileList.toArray(new File[fileList.size()]));
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {
            @Override
            public void onNext(ArrayList<ReferralPicBean> picBeanList) {
                    card_front = picBeanList.get(0).getUrl_big();
                    card_back = picBeanList.get(1).getUrl_big();
                    card_number_pic = picBeanList.get(2).getUrl_big();
                    api.hideDialog();
                    updateFiles();

            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                api.hideDialog();
            }
        });
    }

    private void updateFiles() {
        int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date(System.currentTimeMillis())));
        String age = String.valueOf(currentYear - Year);
        String card_number = "";
        if (null != card_num.getText().toString()) {
            card_number = card_num.getText().toString();
        }

        SubmitFileApi api = new SubmitFileApi(c_type, age, number.getText().toString(), phone.getText().toString(),
                name.getText().toString(), person_sex, sale_mobile, saletype, sale_userid,
                yw_id, card_number, card_number_pic,
                cardprice, card_front, card_back, sale_date);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ErrorCode>() {
            @Override
            public void onNext(ErrorCode resp) {
                if (resp.getError_code().equals("ok")) {
                    ToastUtil.showToast(AddPatientVisitsActivity.this, "提交资料成功");
                    startActivity(new Intent(AddPatientVisitsActivity.this, CardDealListActivity.class));
                    AddPatientVisitsActivity.this.finish();
                    if (null != SaleCardDetailActivity.instance) {
                        SaleCardDetailActivity.instance.finish();
                    }
                } else {
                    if ("00046".equals(resp.getError_code())) {
                        ToastUtil.showToast(mContext, "卡号不存在或卡已被绑定");
                    } else if ("00048".equals(resp.getError_code())) {
                        ToastUtil.showToast(mContext, "该卡为预售不可退，您无权限绑定");
                    } else if ("00049".equals(resp.getError_code())) {
                        ToastUtil.showToast(AddPatientVisitsActivity.this, "该套装的卡号不存在或已绑定");
                    }else {
                    ToastUtil.showToast(AddPatientVisitsActivity.this, "提交资料失败,请重新点击提交");
                    }
                }
            }
        });

    }

    public Boolean vilidInput() {
        String msg = "";
        if (TextUtils.isEmpty(name.getText())) {
            msg = "姓名输入不能为空";
        } else if (TextUtils.isEmpty(phone.getText())) {
            msg = "手机号输入不能为空";
        } else if (phone.getText().toString().length() != 11) {
            msg = "手机号为11位数字，请输入正确的手机号";
        } else if (false == NumberJudgeUtils.isMobileNO(phone.getText().toString())) {
            msg = "手机号格式错误，请输入正确的手机号";
        } else if (StringUtil.isEmpty(number.getText().toString())) {
            msg = "身份证号码不能为空";
        } else if (!StringUtil.isEmpty(isValidID(number.getText().toString()))) {
            msg = isValidID(number.getText().toString());
        } else if (StringUtil.isEmpty(card_num.getText().toString())) {
            msg = "HMO卡卡号不能为空";
        } else if (null == file1 || "".equals(file1.getPath())) {
            msg = "身份证正面照片不能为空，请上传身份证正面照片";
        } else if (null == file2 || "".equals(file2.getPath())) {
            msg = "身份证背面照片不能为空，请上传身份证背面照片";
        } else if (null == file3 || "".equals(file3.getPath())) {
            msg = "卡号照片不能为空，请上传卡号照片";
        }
        if (TextUtils.isEmpty(msg)) {
            return true;
        } else {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 判断是否输入的身份证号格式正确
     *
     * @param personId
     * @return
     */
    public String isValidID(String personId) {
        String msg = IdcardValidator.validate18Idcard(personId);
        if (!StringUtil.isEmpty(msg)) {
            return msg;
        }

        String birth = Year + "" + String.format("%02d", Month) + "" + String.format("%02d", Day);
        if (!birth.equals(personId.substring(6, 14))) {
            msg = "身份证号与出生日期不一致";
            return msg;
        }
        int sex = Integer.parseInt(personId.substring(16, 17));
        if ("0".equals(person_sex) && sex % 2 == 0) {
            msg = "身份证号与性别选择不一致";
            return msg;
        }
        if ("1".equals(person_sex) && sex % 2 == 1) {
            msg = "身份证号与性别选择不一致";
            return msg;
        }
        return msg;
    }


    @Override
    public void onTakePhotoClick() {
        takePhoto();
    }

    @Override
    public void onSelectPicClick() {
        pickPicture();
    }

    private void pickPicture() {
//        if (PermisionUtils.islacksOfPermission(this, PERMISSION[1])) {
//            ToastUtil.showToast(this, "请打开提示对应权限,否则将无法选择您的照片");
//            ActivityCompat.requestPermissions(this, PERMISSION, 1);
//        } else {
//            Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
//            intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
//            startActivity(intent);
//        }
        //2017.11.21权限替换 后期测试没有问题删除注释liujin
        requestPermission();
    }
    private void requestPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
                    intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
                    startActivity(intent);
                } else {
                    Log.e(TAG, "请打开提示对应权限,否则将无法选择您的照片");
                    PermisionUtils.dialog(AddPatientVisitsActivity.this, "请打开提示对应权限,否则将无法选择您的照片");
                }
            }
        });


    }


    public void takePhoto() {
//        if (PermisionUtils.islacksOfPermission(AddPatientVisitsActivity.this, PERMISSION[0])) {
//            ToastUtil.showToast(this, "请打开提示对应权限,否则将影响拍照功能无法使用");
//            ActivityCompat.requestPermissions(this, PERMISSION, 0);
//        } else {
//            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//            File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
//            if (!vFile.exists()) {
//                File vDirPath = vFile.getParentFile();
//                vDirPath.mkdirs();
//            } else {
//                if (vFile.exists()) {
//                    vFile.delete();
//                }
//            }
//            path = vFile.getPath();
//            Uri cameraUri;
//            if (Build.VERSION.SDK_INT >= 24) {
//                cameraUri = FileProvider.getUriForFile(this.getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
//            } else {
//                cameraUri = Uri.fromFile(vFile);
//            }
//            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
//            startActivityForResult(openCameraIntent, TAKE_PICTURE);
//        }
        //2017.11.21权限替换 后期测试没有问题删除注释liujin
        requestTakePicPermission();
    }

    private void requestTakePicPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
                    if (!vFile.exists()) {
                        File vDirPath = vFile.getParentFile();
                        vDirPath.mkdirs();
                    } else {
                        if (vFile.exists()) {
                            vFile.delete();
                        }
                    }
                    path = vFile.getPath();
                    Uri cameraUri;
                    if (Build.VERSION.SDK_INT >= 24) {
                        cameraUri = FileProvider.getUriForFile(getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
                    } else {
                        cameraUri = Uri.fromFile(vFile);
                    }
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
                    startActivityForResult(openCameraIntent, TAKE_PICTURE);

                } else {
                    Log.e(TAG, "请打开提示对应权限,否则将影响拍照功能无法使用");
                    PermisionUtils.dialog(AddPatientVisitsActivity.this, "请打开提示对应权限,否则将影响拍照功能无法使用");
                }
            }
        });
    }

    public void onEvent(ImageEvent event) {
        if (event == null)
            return;

        Collection<ImageItem> collection = event.getCollection();

        for (ImageItem item : collection) {// 目前只能选择一张图片，可上传多张图片时，需根据接口定义修改s
            XHLog.e("sourcePath=" + item.getSourcePath());
            initImageFiles(item);
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKE_PICTURE&&resultCode==RESULT_OK) {
            ImageItem item = new ImageItem();
            item.sourcePath = path;
            XHLog.e("sourcePath=" + item.sourcePath);
            initImageFiles(item);
        }
    }
    private void initImageFiles(ImageItem item){
        String fileName=xhwl.insurance.util.BitmapUtil.handleImage(mContext,item.sourcePath,200);
        if (flag == 1) {
            file1 = new File(fileName);
            ImageDisplayer.getInstance(mContext).displayBmp(id_front, item.thumbnailPath, item.sourcePath);
        } else if (flag == 2) {
            file2 = new File(fileName);
            ImageDisplayer.getInstance(mContext).displayBmp(id_back, item.thumbnailPath, item.sourcePath);
        } else if (flag == 3) {
            file3 = new File(fileName);
            ImageDisplayer.getInstance(mContext).displayBmp(hmo_pic, item.thumbnailPath, item.sourcePath);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        //清空缓存的图片
//        DataCleanManager.deleteFilesByDirectory(new File(mContext.getCacheDir().getAbsolutePath()+ File.separator+"image"));
    }

    void getSaleInfo() {
        SaleInfoApi api = new SaleInfoApi();
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<SaleInfoResp>() {
            @Override
            public void onNext(SaleInfoResp resp) {
                sale_userid = resp.user_id;
                sale_mobile = resp.link_mobile;
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePhoto();
                } else {
                    ToastUtil.showToast(this, "请您打开本应用的拍照权限,否则将无法拍照");
                }
                break;
            case 1:
                if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    pickPicture();
                } else {
                    ToastUtil.showToast(this, "请您打开本应用的读取存储权限,否则将无法获取相册照片");
                }
                break;
        }
    }
}
